package server

import (
	"data_service/models"
	"errors"
	"gorm.io/gorm"
)

// PostService 提供动态相关业务逻辑
// 供 handler 层调用，解耦 handler 与 models
// 只负责业务流程，不直接操作数据库

type PostService struct{}

func NewPostService() *PostService {
	return &PostService{}
}

// CreatePost 创建新动态
func (s *PostService) CreatePost(post *models.Post) error {
	return models.GetDB().Create(post).Error
}

// GetRecentPosts 获取最新动态
func (s *PostService) GetRecentPosts(limit int) ([]models.Post, error) {
	var posts []models.Post
	err := models.GetDB().Order("created_at desc").Limit(limit).Preload("User").Find(&posts).Error
	return posts, err
}

// GetAllPosts 获取所有动态
func (s *PostService) GetAllPosts(userId uint) ([]map[string]interface{}, error) {
	var posts []models.Post
	if err := models.GetDB().Order("created_at desc").Preload("User").Find(&posts).Error; err != nil {
		return nil, err
	}

	result := make([]map[string]interface{}, len(posts))
	for i, post := range posts {
		// 检查当前用户是否点赞
		var likeCount int64
		models.GetDB().Model(&models.PostLike{}).Where("post_id = ? AND user_id = ?", post.ID, userId).Count(&likeCount)
		isLiked := likeCount > 0

		// 构建返回结果
		result[i] = map[string]interface{}{
			"id":         post.ID,
			"user_id":    post.UserID,
			"user":       post.User,
			"content":    post.Content,
			"image_url":  post.ImageURL,
			"likes":      post.Likes,
			"is_liked":   isLiked,
			"created_at": post.CreatedAt,
		}
	}
	
	return result, nil
}

// GetPostsByUser 获取指定用户的所有动态
func (s *PostService) GetPostsByUser(userId string) ([]models.Post, error) {
	var posts []models.Post
	err := models.GetDB().Where("user_id = ?", userId).Preload("User").Find(&posts).Error
	return posts, err
}

// LikePost 给动态点赞
func (s *PostService) LikePost(postId uint, userId uint) (bool, int, error) {
	// 检查动态是否存在
	var post models.Post
	if err := models.GetDB().First(&post, postId).Error; err != nil {
		return false, 0, err
	}

	// 检查用户是否已经点赞
	var like models.PostLike
	result := models.GetDB().Where("post_id = ? AND user_id = ?", postId, userId).First(&like)

	if result.Error == nil {
		// 用户已点赞，执行取消点赞
		if err := models.GetDB().Delete(&like).Error; err != nil {
			return false, 0, err
		}
		post.Likes--
		if err := models.GetDB().Save(&post).Error; err != nil {
			return false, 0, err
		}
		return false, post.Likes, nil
	} else if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		// 用户未点赞，执行点赞
		newLike := models.PostLike{PostID: postId, UserID: userId}
		if err := models.GetDB().Create(&newLike).Error; err != nil {
			return false, 0, err
		}
		post.Likes++
		if err := models.GetDB().Save(&post).Error; err != nil {
			return false, 0, err
		}
		return true, post.Likes, nil
	} else {
		// 其他错误
		return false, 0, result.Error
	}
}

// DeletePost 删除动态
func (s *PostService) DeletePost(postId string) error {
	return models.GetDB().Delete(&models.Post{}, postId).Error
}
